#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown to Word Converter
将Markdown文件转换为Word文档
"""

import re
import os
from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml.shared import OxmlElement, qn

def setup_styles(doc):
    """设置文档样式"""
    # 设置标题样式
    for i in range(1, 7):
        style_name = f'Heading {i}'
        if style_name in doc.styles:
            heading = doc.styles[style_name]
            heading.font.name = 'Microsoft YaHei'
            heading.font.size = Pt(18 - i * 2)
    
    # 设置正文样式
    normal_style = doc.styles['Normal']
    normal_style.font.name = 'Microsoft YaHei'
    normal_style.font.size = Pt(11)

def parse_markdown_line(line):
    """解析Markdown行，返回类型和内容"""
    line = line.rstrip()
    
    # 标题
    if line.startswith('#'):
        level = 0
        for char in line:
            if char == '#':
                level += 1
            else:
                break
        content = line[level:].strip()
        return 'heading', level, content
    
    # 代码块开始/结束
    if line.startswith('```'):
        return 'code_fence', 0, line[3:]
    
    # 列表项
    if re.match(r'^\s*[-*+]\s+', line):
        indent = len(line) - len(line.lstrip())
        content = re.sub(r'^\s*[-*+]\s+', '', line)
        return 'list_item', indent, content
    
    # 数字列表
    if re.match(r'^\s*\d+\.\s+', line):
        indent = len(line) - len(line.lstrip())
        content = re.sub(r'^\s*\d+\.\s+', '', line)
        return 'numbered_list', indent, content
    
    # 表格行
    if '|' in line and line.strip().startswith('|'):
        return 'table_row', 0, line.strip()
    
    # 分隔线
    if re.match(r'^-{3,}$', line.strip()):
        return 'separator', 0, ''
    
    # 空行
    if not line.strip():
        return 'empty', 0, ''
    
    # 普通段落
    return 'paragraph', 0, line

def convert_markdown_to_word(md_file_path, output_path):
    """将Markdown文件转换为Word文档"""
    
    # 创建Word文档
    doc = Document()
    setup_styles(doc)
    
    # 读取Markdown文件
    with open(md_file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    in_code_block = False
    code_content = []
    table_rows = []
    in_table = False
    
    for line in lines:
        line_type, level, content = parse_markdown_line(line)
        
        # 处理代码块
        if line_type == 'code_fence':
            if in_code_block:
                # 结束代码块
                if code_content:
                    code_para = doc.add_paragraph()
                    code_run = code_para.add_run('\n'.join(code_content))
                    code_run.font.name = 'Consolas'
                    code_run.font.size = Pt(9)
                    # 设置代码块背景色（简化处理）
                code_content = []
                in_code_block = False
            else:
                # 开始代码块
                in_code_block = True
            continue
        
        if in_code_block:
            code_content.append(line.rstrip())
            continue
        
        # 处理表格
        if line_type == 'table_row':
            if not in_table:
                in_table = True
                table_rows = []
            table_rows.append(content)
            continue
        else:
            if in_table:
                # 结束表格，创建表格
                if table_rows:
                    create_table(doc, table_rows)
                in_table = False
                table_rows = []
        
        # 处理其他内容
        if line_type == 'heading':
            if level <= 6:
                doc.add_heading(content, level)
        
        elif line_type == 'list_item':
            para = doc.add_paragraph(content, style='List Bullet')
        
        elif line_type == 'numbered_list':
            para = doc.add_paragraph(content, style='List Number')
        
        elif line_type == 'separator':
            # 添加分隔线（简化为空段落）
            doc.add_paragraph()
        
        elif line_type == 'paragraph' and content:
            doc.add_paragraph(content)
        
        elif line_type == 'empty':
            # 空行，添加空段落
            doc.add_paragraph()
    
    # 处理最后的表格
    if in_table and table_rows:
        create_table(doc, table_rows)
    
    # 保存文档
    doc.save(output_path)
    print(f"转换完成！Word文档已保存到: {output_path}")

def create_table(doc, table_rows):
    """创建表格"""
    if not table_rows:
        return
    
    # 解析表格数据
    parsed_rows = []
    for row in table_rows:
        # 移除首尾的|，然后分割
        cells = [cell.strip() for cell in row.strip('|').split('|')]
        if cells and any(cell.strip() for cell in cells):  # 忽略空行或分隔行
            if not all(re.match(r'^[-:]+$', cell.strip()) for cell in cells):  # 忽略分隔行
                parsed_rows.append(cells)
    
    if not parsed_rows:
        return
    
    # 创建表格
    max_cols = max(len(row) for row in parsed_rows)
    table = doc.add_table(rows=len(parsed_rows), cols=max_cols)
    table.style = 'Table Grid'
    
    # 填充表格数据
    for i, row_data in enumerate(parsed_rows):
        for j, cell_data in enumerate(row_data):
            if j < max_cols:
                table.cell(i, j).text = cell_data

if __name__ == "__main__":
    # 输入和输出文件路径
    input_file = "cerebellar_platform_spec_ui_upgraded(1).md"
    output_file = "cerebellar_platform_spec_ui_upgraded.docx"
    
    try:
        convert_markdown_to_word(input_file, output_file)
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        print("请确保已安装 python-docx 库: pip install python-docx")
